// pages/pay/order-detail/index.js
const apiService = require('../../../utils/api.js');
const auth = require('../../../utils/auth.js');
const setting = require('../../../setting/setting.js');
const app = getApp();

Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		appointmentId: '', // 预约ID
		appointmentData: null, // 预约数据
		statusBarHeight: 44, // 系统状态栏高度
		orderStatus: 'pending', // 订单状态：pending(待支付)、paid(支付成功)、cancelled(已取消)
		countdown: 0, // 支付倒计时（秒）
		countdownTimer: null, // 倒计时定时器
		countdownDisplay: '', // 倒计时显示文本
		isLoading: false, // 加载状态
		
		// 导航栏滚动状态
		scrollY: 0,
		navbarOpacity: 0,  // 导航栏背景透明度 (0-1)
		navbarTextColor: '#333333' // 导航栏文字颜色
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad(options) {
		// 初始化 DataManager
		this.dataManager = app.dataManager;
		// 获取系统信息
		this.getSystemInfo();
		
		// 处理参数兼容：支持 appointmentId、appointmentNumber、out_trade_no
		const appointmentId = options.appointmentId;
		const appointmentNumber = options.appointmentNumber || options.out_trade_no;
		
		if (appointmentId) {
			this.setData({ appointmentId });
			this.checkLoginAndLoadData();
			return;
		}

		if (appointmentNumber) {
			// 通过预约单号查询并解析出 appointmentId 后再加载
			this.resolveAppointmentIdByNumber(appointmentNumber);
			return;
		}

		if (options.orderData) {
			// 兼容旧版本
			this.processOrderData(options.orderData);
		}
	},

	/**
	 * 通过预约单号(或 out_trade_no)解析 appointmentId
	 */
	async resolveAppointmentIdByNumber(appointmentNumber) {
		try {
			// 简单分页查找，最多查前几页以避免长时间等待
			const MAX_PAGES = 5;
			const PAGE_SIZE = 20;
			let found = null;
			for (let page = 1; page <= MAX_PAGES; page++) {
				const res = await apiService.getMyAppointments(null, page, PAGE_SIZE);
				if (res && res.success && res.data && Array.isArray(res.data.list)) {
					found = res.data.list.find(item => item.appointmentNumber === appointmentNumber);
					if (found) break;
				}
			}
			if (found && found._id) {
				this.setData({ appointmentId: found._id });
				this.checkLoginAndLoadData();
			} else {
				wx.showToast({ title: '未找到对应订单', icon: 'none' });
			}
		} catch (e) {
			console.error('resolveAppointmentIdByNumber error:', e);
			wx.showToast({ title: '订单查询失败', icon: 'none' });
		}
	},

	/**
	 * 获取系统信息
	 */
	getSystemInfo() {
		const systemInfo = wx.getSystemInfoSync();
		this.setData({
			statusBarHeight: systemInfo.statusBarHeight || 44
		});
	},

	/**
	 * 返回上一页
	 */
	onBack() {
		try {
			const pages = getCurrentPages();
			const prev = pages[pages.length - 2];
			if (prev && prev.route === 'pages/pay/order-list/index') {
				// 设置一次性标记，返回后列表页 onShow 不刷新
				wx.setStorageSync('skipOrderListRefreshOnce', true);
				wx.navigateBack({ delta: 1 });
				return;
			}
		} catch (e) {}
	
		// 保留原有逻辑
		if (this.data.orderStatus === 'paid') {
			wx.switchTab({ url: '/pages/home/index/index' });
		} else {
			wx.navigateBack({
				delta: 1,
				fail: () => {
					wx.switchTab({ url: '/pages/home/index/index' });
				}
			});
		}
	},

	/**
	 * 检查登录状态并加载数据
	 */
	async checkLoginAndLoadData() {
		if (!auth.checkLoginStatus()) {
			// 未登录，显示提示并跳转到登录页
			wx.showModal({
				title: '请先登录',
				content: '查看订单详情需要先登录账号',
				confirmText: '去登录',
				cancelText: '返回',
				success: (res) => {
					if (res.confirm) {
						auth.requireLogin(`/pages/pay/order-detail/index?appointmentId=${this.data.appointmentId}`);
					} else {
						wx.navigateBack({
							delta: 1,
							fail: () => {
								wx.switchTab({
									url: '/pages/home/index/index'
								});
							}
						});
					}
				}
			});
			return;
		}
		
		// 已登录，加载预约详情
		await this.loadAppointmentDetail();
	},

	/**
	 * 加载预约详情
	 */
	async loadAppointmentDetail() {
		this.setData({ isLoading: true });

		try {
			const result = await apiService.getAppointmentDetail(this.data.appointmentId);
			if (result.success) {
				this.setData({
					appointmentData: result.data,
					isLoading: false
				});
				this.computeDisplayFields();
				this.initOrderStatus();
			} else {
				throw new Error(result.message);
			}
		} catch (error) {
			console.error('加载预约详情失败:', error);
			this.setData({ isLoading: false });
			wx.showToast({
				title: '加载失败',
				icon: 'none'
			});
		}
	},

	/**
	 * 处理订单数据（兼容旧版本）
	 */
	processOrderData(orderDataStr) {
		try {
			const orderData = JSON.parse(decodeURIComponent(orderDataStr));
			this.setData({ appointmentData: orderData });
			this.computeDisplayFields();
			console.log('接收到订单数据：', orderData);
			this.initOrderStatus();
		} catch (error) {
			console.error('解析订单数据失败：', error);
			wx.showToast({
				title: '数据解析失败',
				icon: 'none'
			});
		}
	},

	/**
	 * 初始化订单状态
	 */
	initOrderStatus() {
		const appointmentData = this.data.appointmentData;
		if (!appointmentData) return;

		// 根据预约状态设置订单状态
		let orderStatus = 'pending';
		switch (appointmentData.status) {
			case 101: // 待支付
				orderStatus = 'pending';
				break;
			case 201: // 已支付
			case 301: // 服务中
			case 302: // 已完成
				orderStatus = 'paid';
				break;
			case 401: // 已取消
				orderStatus = 'cancelled';
				break;
		}

		// 设置倒计时（待支付状态）
		const countdown = orderStatus === 'pending' ? 12 * 3600 : 0;

		this.setData({
			orderStatus: orderStatus,
			countdown: countdown
		});

		// 如果是待支付状态，启动倒计时
		if (orderStatus === 'pending') {
			this.startCountdown();
		}
	},

	/**
	 * 启动支付倒计时
	 */
	startCountdown() {
		// 启动前先清除旧的倒计时，避免重复定时器导致异常
		this.clearCountdown();
	
		// 若当前倒计时已到或非正值，仅更新显示，不再启动
		if (this.data.countdown <= 0) {
			this.updateCountdownDisplay();
			return;
		}
	
		this.updateCountdownDisplay();
	
		this.data.countdownTimer = setInterval(() => {
			// 非待支付状态（例如已支付/已取消）不应继续倒计时
			if (this.data.orderStatus !== 'pending') {
				this.clearCountdown();
				return;
			}
	
			if (this.data.countdown <= 0) {
				// 倒计时结束，订单自动取消
				this.handleOrderTimeout();
				return;
			}
	
			this.setData({
				countdown: this.data.countdown - 1
			});
			this.updateCountdownDisplay();
		}, 1000);
	},

	/**
	 * 更新倒计时显示
	 */
	updateCountdownDisplay() {
		const countdown = this.data.countdown;
		const hours = Math.floor(countdown / 3600);
		const minutes = Math.floor((countdown % 3600) / 60);
		const seconds = countdown % 60;
		const display = `${hours}小时${minutes}分${seconds}秒`;
		this.setData({ countdownDisplay: display });
	},

	/**
	 * 处理订单超时
	 */
	handleOrderTimeout() {
		// 若当前已不是待支付状态（例如已支付），忽略过期定时器的触发
		if (this.data.orderStatus !== 'pending') {
			this.clearCountdown();
			return;
		}
	
		this.clearCountdown();
		this.setData({
			orderStatus: 'cancelled'
		});
		
		wx.showToast({
			title: '订单已超时取消',
			icon: 'none',
			duration: 2000
		});
	},

	/**
	 * 清除倒计时
	 */
	clearCountdown() {
		if (this.data.countdownTimer) {
			clearInterval(this.data.countdownTimer);
			this.setData({
				countdownTimer: null
			});
		}
	},

	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady() {

	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	async onShow() {
		// 验证登录状态
		const isLoggedIn = await auth.validateLoginStatus();
		if (isLoggedIn) {
			// 刷新订单详情
			if (this.data.appointmentId) {
				await this.loadAppointmentDetail();
			}
		} else {
			// 登录状态失效，重新检查
			this.checkLoginAndLoadData();
		}
	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide() {

	},

	/**
	 * 取消订单
	 */
	handleCancelOrder() {
		wx.showModal({
			title: '确认取消',
			content: '确定要取消这个订单吗？',
			success: (res) => {
				if (res.confirm) {
					this.cancelAppointment();
				}
			}
		});
	},

	/**
	 * 取消预约
	 */
	async cancelAppointment() {
		// 验证登录状态
		if (!auth.checkLoginStatus()) {
			wx.showModal({
				title: '登录已过期',
				content: '请重新登录后再试',
				confirmText: '去登录',
				success: (res) => {
					if (res.confirm) {
						auth.requireLogin(`/pages/pay/order-detail/index?appointmentId=${this.data.appointmentId}`);
					}
				}
			});
			return;
		}

		try {
			wx.showLoading({ title: '取消中...' });
			
			const result = await apiService.cancelAppointment(this.data.appointmentId);
			
			if (result.success) {
				// 清除倒计时
				this.clearCountdown();
				
				// 更新订单状态
				this.setData({
					orderStatus: 'cancelled'
				});
				
				wx.hideLoading();
				wx.showToast({
					title: '订单已取消',
					icon: 'success',
					duration: 2000
				});
			} else {
				throw new Error(result.message);
			}
		} catch (error) {
			wx.hideLoading();
			console.error('取消预约失败:', error);
			wx.showToast({
				title: error.message || '取消失败',
				icon: 'none'
			});
		}
	},

	/**
	 * 支付订单
	 */
	async handlePayOrder() {
		// 验证登录状态
		if (!auth.checkLoginStatus()) {
			wx.showModal({
				title: '登录已过期',
				content: '请重新登录后再试',
				confirmText: '去登录',
				success: (res) => {
					if (res.confirm) {
						auth.requireLogin(`/pages/pay/order-detail/index?appointmentId=${this.data.appointmentId}`);
					}
				}
			});
			return;
		}

		try {
			wx.showLoading({ title: '正在支付...', mask: true });

			const appointmentId = this.data.appointmentId;
			if (!appointmentId) throw new Error('订单信息不完整');

			// 1) 先尝试余额支付
			const balanceRes = await apiService.payWithBalance(appointmentId);
			if (balanceRes && balanceRes.success) {
				// 支付成功
				this.setData({ orderStatus: 'paid' });
				this.clearCountdown();
				wx.hideLoading();
				wx.showToast({ title: '支付成功', icon: 'success', duration: 1800 });
				
				// 清除用户相关缓存，确保个人中心页面能获取最新余额
				const app = getApp();
				const dataManager = app.getDataManager();
				dataManager.invalidateUserCache();
				console.log('[余额支付成功] 已清除用户缓存');
				
				// 通知个人中心页面刷新数据
				const pages = getCurrentPages();
				const profilePage = pages.find(page => page.route === 'pages/main/user-profile/index');
				if (profilePage && typeof profilePage.refreshUserData === 'function') {
					console.log('[余额支付成功] 通知个人中心页面刷新数据');
					profilePage.refreshUserData();
				}
				
				// 刷新详情
				await this.loadAppointmentDetail();
				return;
			}

			// 2) 余额不足或失败，走微信支付
			const payRes = await apiService.createPayment(appointmentId);
			if (!payRes.success || !payRes.data || !payRes.data.paymentParams) {
				throw new Error(payRes.message || '创建支付订单失败');
			}
			let paymentParams = payRes.data.paymentParams;
			// TEST_MODE 兼容服务端字段 _isTestMode
			if (paymentParams._isTestMode) {
				await this.requestWxPayment({ ...paymentParams, testMode: true });
				// 支付成功后通知后端更新状态（云函数模式下）
				if (!setting.USE_SELF_BACKEND_PAYMENT) {
					try {
						await apiService.handlePaymentCallback(appointmentId, { paymentResult: { status: 'success' } });
					} catch (e) {
						console.warn('支付成功回调调用失败:', e);
					}
				}
				// 支付成功后刷新详情和订单列表缓存
				await this.loadAppointmentDetail();
				// 刷新订单列表缓存
				this.dataManager.getOrderList({}, true).catch(err => {
					console.warn('刷新订单列表缓存失败:', err);
				});
				return;
			}

			paymentParams = apiService.normalizeWxPaymentParams(paymentParams);
			await this.requestWxPayment(paymentParams);
			// 支付成功后通知后端更新状态（云函数模式下）
			if (!setting.USE_SELF_BACKEND_PAYMENT) {
				try {
					await apiService.handlePaymentCallback(appointmentId, { paymentResult: { status: 'success' } });
				} catch (e) {
					console.warn('支付成功回调调用失败:', e);
				}
			}
			// 支付成功后刷新详情和订单列表缓存
			await this.loadAppointmentDetail();
			// 刷新订单列表缓存
			this.dataManager.getOrderList({}, true).catch(err => {
				console.warn('刷新订单列表缓存失败:', err);
			});
		} catch (error) {
			wx.hideLoading();
			const msg = error && error.message ? error.message : String(error);
			// 若余额不足、或后端明确提示余额不足
			if (/余额不足/.test(msg)) {
				// 引导用户充值或继续微信支付：这里已自动走微信支付流程，上面逻辑会覆盖
				wx.showToast({ title: '余额不足，已转微信支付', icon: 'none' });
			} else {
				wx.showToast({ title: msg || '支付失败', icon: 'none' });
			}
			console.error('支付失败:', error);
		}
	},

	/**
	 * 调用微信支付
	 */
	async requestWxPayment(paymentParams) {
	// TEST_MODE: 模拟支付，无需调用 wx.requestPayment
	if (paymentParams && paymentParams.testMode) {
		wx.hideLoading();
		this.setData({ orderStatus: 'paid' });
		this.clearCountdown();
		wx.showToast({ title: '模拟支付成功', icon: 'success', duration: 2000 });
		// 调用后端回调（云函数模式下），保持数据一致
		if (!setting.USE_SELF_BACKEND_PAYMENT) {
			try {
				await apiService.handlePaymentCallback(this.data.appointmentId, { paymentResult: { status: 'success', testMode: true } });
			} catch (e) {
				console.warn('模拟支付回调调用失败:', e);
			}
		}
		
		// 清除用户相关缓存，确保个人中心页面能获取最新余额
		const app = getApp();
		const dataManager = app.getDataManager();
		dataManager.invalidateUserCache();
		console.log('[模拟支付成功] 已清除用户缓存');
		
		// 通知个人中心页面刷新数据
		const pages = getCurrentPages();
		const profilePage = pages.find(page => page.route === 'pages/main/user-profile/index');
		if (profilePage && typeof profilePage.refreshUserData === 'function') {
			console.log('[模拟支付成功] 通知个人中心页面刷新数据');
			profilePage.refreshUserData();
		}
		
		// 刷新订单列表缓存
		this.dataManager.getOrderList({}, true).catch(err => {
			console.warn('刷新订单列表缓存失败:', err);
		});
		return Promise.resolve({ errMsg: 'requestPayment:ok', testMode: true });
	}
	// 归一化支付参数，提升容错能力
	paymentParams = apiService.normalizeWxPaymentParams(paymentParams);
	return new Promise((resolve, reject) => {
		wx.requestPayment({
			timeStamp: paymentParams.timeStamp,
			nonceStr: paymentParams.nonceStr,
			package: paymentParams.package,
			signType: paymentParams.signType,
			paySign: paymentParams.paySign,
			success: async (res) => {
				wx.hideLoading();
				// 支付成功，更新订单状态
				this.setData({
					orderStatus: 'paid'
				});
				this.clearCountdown();
				wx.showToast({
					title: '支付成功',
					icon: 'success',
					duration: 2000
				});
				
				// 清除用户相关缓存，确保个人中心页面能获取最新余额
				const app = getApp();
				const dataManager = app.getDataManager();
				dataManager.invalidateUserCache();
				console.log('[微信支付成功] 已清除用户缓存');
				
				// 通知个人中心页面刷新数据
				const pages = getCurrentPages();
				const profilePage = pages.find(page => page.route === 'pages/main/user-profile/index');
				if (profilePage && typeof profilePage.refreshUserData === 'function') {
					console.log('[微信支付成功] 通知个人中心页面刷新数据');
					profilePage.refreshUserData();
				}
				
				resolve(res);
			},
			fail: (error) => {
				wx.hideLoading();
				if (error.errMsg.includes('cancel')) {
					wx.showToast({
						title: '支付已取消',
						icon: 'none'
					});
				} else {
					wx.showToast({
						title: '支付失败',
						icon: 'none'
					});
				}
				reject(error);
			}
		});
	});
	},

	/**
	 * 跳转到店铺详情
	 */
	handleShopDetail() {
		wx.showToast({
			title: '跳转到店铺详情',
			icon: 'none',
			duration: 1000
		});
		// 实际项目中应跳转到店铺详情页
		// wx.navigateTo({
		//   url: '/pages/shop/detail/index?id=xxx'
		// });
	},

	/**
	 * 测试方法：切换订单状态（仅用于演示）
	 */
	switchOrderStatus() {
		const statusMap = {
			'pending': 'paid',
			'paid': 'cancelled',
			'cancelled': 'pending'
		};
		
		const newStatus = statusMap[this.data.orderStatus];
		
		// 清除倒计时
		this.clearCountdown();
		
		this.setData({
			orderStatus: newStatus
		});
		
		// 如果切换到待支付状态，重新启动倒计时
		if (newStatus === 'pending') {
			this.setData({
				countdown: 12 * 3600 + 30 * 60 + 58
			});
			this.startCountdown();
		}
		
		// 更新支付时间
		if (newStatus === 'paid') {
			const now = new Date();
			const payTime = `${now.getFullYear()}-${(now.getMonth() + 1).toString().padStart(2, '0')}-${now.getDate().toString().padStart(2, '0')} ${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}:${now.getSeconds().toString().padStart(2, '0')}`;
			this.setData({
				'orderData.serviceInfo.payTime': payTime
			});
		}
		
		wx.showToast({
			title: `切换到${newStatus === 'pending' ? '待支付' : newStatus === 'paid' ? '支付成功' : '已取消'}状态`,
			icon: 'none',
			duration: 1500
		});
	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload() {
		// 清除倒计时
		this.clearCountdown();
	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh() {

	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom() {

	},

	/**
	 * 页面滚动监听
	 */
	onPageScroll(e) {
		const scrollY = e.scrollTop;
		
		// 计算导航栏背景透明度，滚动距离0-100px内从透明变为不透明
		const maxScrollDistance = 100; // 滚动距离阈值（像素）
		const opacity = Math.min(scrollY / maxScrollDistance, 1);
		
		// 计算文字颜色，透明度达到0.5时开始变黑
		const textColor = opacity >= 0.5 ? '#120E0C' : '#333333';
		
		// 只有在透明度或文字颜色发生变化时才更新
		if (this.data.navbarOpacity !== opacity || this.data.navbarTextColor !== textColor) {
			this.setData({
				scrollY: scrollY,
				navbarOpacity: opacity,
				navbarTextColor: textColor
			});
		}
	},

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage() {

	},

	computeDisplayFields() {
		const ad = this.data.appointmentData;
		if (!ad) return;
		
		console.log('订单详情数据:', ad);
		
		let pet = {};
		if (ad.petIds && ad.petIds.length > 0) {
			if (ad.petList && ad.petList.length > 0) {
				pet = ad.petList[0];
			} else {
				pet = ad.petInfo || {};
			}
		}
		const category = pet.category || '';
		const defaultAvatar = /狗/.test(category) ? '/assets/common/img_dog_avatar_default.png' : (/猫/.test(category) ? '/assets/common/img_cat_avatar_default.png' : '/assets/common/img_cat_avatar_default.png');
		const rawAvatar = pet.avatar || pet.imageUrl || pet.image || '';
		const isValidAvatar = typeof rawAvatar === 'string' && (rawAvatar.startsWith('https://') || rawAvatar.startsWith('cloud://') || rawAvatar.startsWith('/assets/'));
		const avatar = isValidAvatar ? rawAvatar : defaultAvatar;
		const petIcon = /狗/.test(category) ? '/assets/pet/icon_dog_choice.png' : '/assets/pet/icon_cat_choice.png';
		const name = pet.name || '';
		const breed = pet.breed || pet.category || pet.species || '';
		const age = pet.age ? `${pet.age}个月` : '';
		const weight = pet.weight ? `体重${pet.weight}kg` : '';
		const petDetails = [breed, age, weight].filter(Boolean).join(' | ');
		
		// 预约时间 - 修复时间戳转换
		const appointmentTime = ad.appointmentTime;
		const createTime = ad.createTime;
		const payTime = ad.payTime;
		const rechargeTs = payTime || ad.updateTime || createTime; // 充值时间优先展示支付时间，其次更新时间，最后创建时间
		const appointmentEndTime = ad.appointmentEndTime;
		const roomUnit = ad.roomUnit || '天'; // 房间收费单位
		let fosterDays = 0;
		let endDate = '';
		
		// 根据房间收费单位决定显示的预约时间
		const displayTime = roomUnit === '小时' ? createTime : appointmentTime;
		
		// 对于寄养服务（按天计费），优先使用totalDays计算显示日期
		if (roomUnit === '天' && ad.totalDays && ad.totalDays > 0 && appointmentTime) {
			const toMs = (ts) => {
				const n = typeof ts === 'number' ? ts : parseInt(ts, 10);
				if (isNaN(n)) return 0;
				return n >= 1e12 ? n : n * 1000; // 13位视为毫秒，10位视为秒
			};
			const startDate = new Date(toMs(appointmentTime));
			const startYear = startDate.getFullYear();
			const startMonth = startDate.getMonth();
			const startDay = startDate.getDate();
			
			// 使用totalDays计算结束日期：开始日期 + (totalDays - 1) 天
			const endDateCalc = new Date(startYear, startMonth, startDay + (ad.totalDays - 1));
			const endYear = endDateCalc.getFullYear();
			const endMonth = endDateCalc.getMonth();
			const endDay = endDateCalc.getDate();
			
			// 格式化为起始-结束日期
			const startDateStr = `${startYear}-${String(startMonth + 1).padStart(2, '0')}-${String(startDay).padStart(2, '0')}`;
			const endDateStr = `${endYear}-${String(endMonth + 1).padStart(2, '0')}-${String(endDay).padStart(2, '0')}`;
			endDate = `${startDateStr} 至 ${endDateStr}`;
			
			// 使用totalDays作为天数
			fosterDays = ad.totalDays;
		} else if (appointmentTime && appointmentEndTime) {
			// 对于按小时计费的服务，使用appointmentEndTime计算
			const toMs = (ts) => {
				const n = typeof ts === 'number' ? ts : parseInt(ts, 10);
				if (isNaN(n)) return 0;
				return n >= 1e12 ? n : n * 1000; // 13位视为毫秒，10位视为秒
			};
			const startDate = new Date(toMs(appointmentTime));
			const endDateObj = new Date(toMs(appointmentEndTime));
			
			// 获取起始和结束日期的年月日（忽略时分秒）
			const startYear = startDate.getFullYear();
			const startMonth = startDate.getMonth();
			const startDay = startDate.getDate();
			const endYear = endDateObj.getFullYear();
			const endMonth = endDateObj.getMonth();
			const endDay = endDateObj.getDate();
			
			// 创建只包含日期的Date对象进行比较（使用0点时间，避免时区问题）
			const startDateOnly = new Date(Date.UTC(startYear, startMonth, startDay, 0, 0, 0));
			const endDateOnly = new Date(Date.UTC(endYear, endMonth, endDay, 0, 0, 0));
			
			// 计算两个日期之间的自然日差值（毫秒转天数）
			const diffMs = endDateOnly.getTime() - startDateOnly.getTime();
			const diffDays = Math.floor(diffMs / (24 * 3600 * 1000));
			
			// 包含起始和结束日期，所以+1（10-24到10-25：1+1=2天）
			fosterDays = diffDays + 1;
			
			if (fosterDays < 1) fosterDays = 1; // 至少1天
			
			// 格式化为起始-结束日期
			const startDateStr = `${startYear}-${String(startMonth + 1).padStart(2, '0')}-${String(startDay).padStart(2, '0')}`;
			const endDateStr = `${endYear}-${String(endMonth + 1).padStart(2, '0')}-${String(endDay).padStart(2, '0')}`;
			endDate = `${startDateStr} 至 ${endDateStr}`;
		}
		
		// 价格
		const totalPriceYuan = (ad.totalAmount || ad.payAmount || 0) / 100;
		
		// 联系人信息
		const contactName = ad.contactName || '';
		const contactPhone = ad.contactPhone || '';
		const contact = contactName + (contactPhone ? ` (${contactPhone})` : '');
		
		console.log('联系人信息调试:', {
			contactName: ad.contactName,
			contactPhone: ad.contactPhone,
			remarks: ad.remarks,
			finalContact: contact
		});
		
		// 时间格式化函数
		const fmt = (ts) => {
			if (!ts) return '';
			try {
				// 处理时间戳（秒/毫秒）或字符串日期
				let d = null;
				if (typeof ts === 'string' && (ts.includes('-') || ts.includes('T'))) {
					const tmp = new Date(ts);
					if (!isNaN(tmp.getTime())) d = tmp;
				}
				if (!d) {
					const n = typeof ts === 'number' ? ts : parseInt(ts, 10);
					if (isNaN(n)) return '';
					const ms = n >= 1e12 ? n : n * 1000;
					d = new Date(ms);
				}
				if (isNaN(d.getTime())) {
					console.warn('无效的时间戳:', ts);
					return '';
				}
				const Y = d.getFullYear();
				const M = String(d.getMonth() + 1).padStart(2, '0');
				const D = String(d.getDate()).padStart(2, '0');
				const h = String(d.getHours()).padStart(2, '0');
				const m = String(d.getMinutes()).padStart(2, '0');
				const s = String(d.getSeconds()).padStart(2, '0');
				return `${Y}-${M}-${D} ${h}:${m}:${s}`;
			} catch (error) {
				console.error('时间格式化错误:', error, ts);
				return '';
			}
		};
		
		console.log('计算后的显示字段:', {
			pet: { avatar, name, breed, age, weight, petDetails },
			appointmentTime: fmt(appointmentTime),
			fosterDays,
			endDate,
			contact,
			totalPriceYuan,
			createTime: fmt(createTime),
			payTime: fmt(payTime),
			rechargeTime: fmt(rechargeTs)
		});
		
		// 寄养时间显示：如果是寄养订单且有起始结束时间，显示"起始日期 至 结束日期"
		// 复用上面已计算的 endDate（格式为 "起始日期 至 结束日期"）
		let displayFosterTime = '';
		if (roomUnit !== '小时' && endDate) {
			displayFosterTime = endDate;
		}
		
		this.setData({
			displayPetIcon: petIcon,
			displayPetAvatar: avatar,
			displayPetName: name,
			displayPetDetails: petDetails,
			displayBookingTime: roomUnit === '小时' ? fmt(displayTime) : displayFosterTime || fmt(displayTime),
			displayFosterDays: fosterDays,
			displayEndDate: endDate,
			displayFosterTime: displayFosterTime, // 寄养时间范围
			displayContact: contact,
			displayTotalPriceYuan: totalPriceYuan,
			displayCreateTime: fmt(createTime),
			displayPayTime: fmt(rechargeTs), // 充值时间文案绑定此字段
			roomUnit: roomUnit // 保存房间收费单位供模板使用
		});
	}
})
